import { SECOND_FILTER_MORE_MAP } from "../../constant/index";
import api from "../../utils/api";
import { withTokenFn, throttle } from "../../utils/util"; // 引入api接口管理文件
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    feedLoading: false,
    filterMore: SECOND_FILTER_MORE_MAP["down"],
    typeList: [],
    provincesList: [],
    dataList: [],
    pageNum: 1,
    totalPage: 1,
    pageErrorFixed: false,
    pageFooterType: "",
    pageErrorType: "",
    once: false, // 是否是主接口
    chooseTypeItem: null,
    showWaringMessage: false,
    filterResult: {
      areaId: "",
      minDistanceToMax: null,
      minPayPriceToMax: null,
      gender: null,
      vaccineCategoryId: null,
      "injectObjects[]": null,
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.getAreaIdData();
  },

  getAreaIdData() {
    const p1 = this.areaProvinces();
    const p2 = this.vaccineCategoryList();
    Promise.all([p1, p2])
      .then((result) => {
        const [provincesList, typeList] = result || [];
        this.setData({
          typeList,
          provincesList,
        });
        this.getList();
      })
      .catch((err) => {
        console.log("err: ", err);
        this.handlePageError("error");
      });
  },

  /**
   * @description: 获取疫苗类型数据
   */
  vaccineCategoryList() {
    return new Promise((resolve, reject) => {
      return api.vaccineCategoryList({
        // 调用接口，传入参数
        data: {},
        success: (res) => {
          if (+res.code === 0) {
            const dataList = (res.data.dataList || []).filter(item => item.show);
            const newDataList = [
              { id: -100, name: "全部", sortIndex: 1000000 },
            ];
            dataList.forEach((item, index) => {
              if (item.show) {
                item.sortIndex = dataList.length - index;
                newDataList.push(item);
              }
            });
            newDataList.sort((a, b) => b.sortIndex - a.sortIndex);
            resolve(newDataList);
          } else {
            reject();
          }
        },
        fail: (err) => {
          reject();
        },
      });
    });
  },

  /**
   * @description: 获取省份
   */
  areaProvinces() {
    return new Promise((resolve, reject) => {
      return api.areaProvinces({
        // 调用接口，传入参数
        data: {},
        success: (res) => {
          if (+res.code === 0) {
            resolve([{ id: -100, name: "全国" }, ...res.data]);
          } else {
            reject();
          }
        },
        fail: (err) => {
          reject();
        },
      });
    });
  },

  getList() {
    const { pageNum, filterResult } = this.data;
    let data = {
      pageNum,
      pageSize: 10,
      lat: app.globalData.lat,
      lon: app.globalData.lon,
      ...filterResult,
    };
    api.productVaccineProductV2List({
      // 调用接口，传入参数
      data,
      success: (res) => {
        console.log("res: ", res);
        // 报错
        if (+res.code !== 0) {
          return this.handlePageError("error");
        }
        // 无数据
        if (res.data.total <= 0) {
          return this.handlePageError("nodata");
        }

        // 正常数据
        const dataList = this.dataAdatar(res.data.dataList || []);
        this.setData({
          dataList:
            pageNum > 1 ? [...this.data.dataList, ...dataList] : dataList,
          totalPage: res.data.totalPage * 1,
          recommend: res.data.recommend,
          loading: false,
          feedLoading: false,
          once: true,
          pageFooterType: res.data.total <= 10 ? "end" : "", // 数据只够一页
          pageErrorType: "",
        });
      },
      fail: (err) => {
        this.handlePageError("error");
      },
    });
  },

  /**
   * @description: 处理页面异常
   */
  handlePageError(type) {
    const { pageNum, once } = this.data;
    if (pageNum === 1) {
      return this.setData({
        pageErrorType: type,
        pageErrorFixed: !once,
        loading: false,
        feedLoading: false,
      });
    }

    if (pageNum > 1) {
      return this.setData({
        pageFooterType: type,
        loading: false,
        feedLoading: false,
      });
    }
  },

  onRetry() {
    const { once } = this.data;
    this.setData(
      {
        pageFooterType: "ing",
        loading: !once,
      },
      () => {
        if (once) {
          this.getList();
        } else {
          this.getAreaIdData();
        }
      }
    );
  },

  dataAdatar(data) {
    return data.map((item, index) => {
      return {
        id: index,
        ...item,
      };
    });
  },

  onSearch(e) {
    this.setData(
      {
        filterResult: e.detail,
        pageNum: 1,
        feedLoading: true,
        pageErrorType: "",
      },
      () => {
        this.getList();
      }
    );
  },
  onSecondSearch(e) {
    const { typeList } = this.data;
    const { _filterResult, index, _currentSecondFilterSort } = e.detail;
    typeList[index]["sortIndex"] = _currentSecondFilterSort;
    this.setData(
      {
        filterResult: _filterResult,
        typeList: typeList.sort((a, b) => b.sortIndex - a.sortIndex),
        feedLoading: true,
        pageErrorType: "",
        pageNum: 1,
      },
      () => {
        this.choosetype(typeList, 1);
        this.getList();
      }
    );
  },

  jumpSearch() {
    withTokenFn(() => {
      throttle(() => {
        wx.navigateTo({
          url: "../search/index",
        });
      }, 2000);
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const { pageNum, totalPage, pageFooterType } = this.data;
    // 如果还在请求中则退出
    if (pageFooterType === "img") return;
    if (pageNum >= totalPage) {
      this.setData({
        pageFooterType: "end",
      });
    } else {
      this.setData(
        {
          pageNum: this.data.pageNum + 1,
          pageFooterType: "ing",
        },
        () => {
          this.getList();
        }
      );
    }
  },

  choosetype(list, index) {
    this.setData({
      chooseTypeItem: list[index],
    });
  },

  openMessage() {
    this.setData({
      showWaringMessage: true,
    });
  },

  closeMessage() {
    this.setData({
      showWaringMessage: false,
    });
  },
});
